#include "stdafx.h"
#include "FileNamesRetriever.h"
#include <iostream>
#include <string>
#include <list>
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

using namespace std;

typedef basic_string<TCHAR> tstring;

TCHAR* StringToTCHAR(string& s)
{
	tstring tstr;
	const char* all = s.c_str();
	int len = 1 + strlen(all);
	wchar_t* t = new wchar_t[len];
	if (NULL == t) throw bad_alloc();
	mbstowcs_s(NULL, t, len, all, MAX_PATH);
	return (TCHAR*)t;
}

list<string> FileNamesRetriever::Retrieve(string dirName)
{
	WIN32_FIND_DATA ffd;	
	TCHAR szDir[MAX_PATH];
	size_t stringLength;
	HANDLE hFind = INVALID_HANDLE_VALUE;
	DWORD dwError=0;
	list<string> fileNames;

	TCHAR *dirNameCopy = StringToTCHAR(dirName);

	// Check that the input path plus 3 is not longer than MAX_PATH.
	// Three characters are for the "\*" plus NULL appended below.

	StringCchLength(dirNameCopy, MAX_PATH, &stringLength);

	if (stringLength > (MAX_PATH - 3))
	{
		throw "\nDirectory path is too long.\n";
	}

	// Prepare string for use with FindFile functions.  First, copy the
	// string to a buffer, then append '\*' to the directory name.

	StringCchCopy(szDir, MAX_PATH, dirNameCopy);
	StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

	// Find the first file in the directory.

	hFind = FindFirstFile(szDir, &ffd);

	if (INVALID_HANDLE_VALUE == hFind) 
	{
		throw "\nInvalid handle value.\n";
	}

	// Append all file names in the directory to the list.

	do
	{
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{	
			
		}
		else
		{
			size_t origsize = wcslen(ffd.cFileName) + 1;
			const size_t newsize = 100;
			size_t convertedChars = 0;
			char nstring[newsize];
			wcstombs_s(&convertedChars, nstring, origsize, ffd.cFileName, _TRUNCATE);
			fileNames.push_back(nstring);
		}
	}
	while (FindNextFile(hFind, &ffd) != 0);

	dwError = GetLastError();
	if (dwError != ERROR_NO_MORE_FILES) 
	{
		throw "\nSome error occurred.\n";
	}

	FindClose(hFind);
	return fileNames;
}
